import 'dart:typed_data';
import 'dart:ui';

import 'package:flutter/material.dart';
import 'package:flutter/rendering.dart';
import 'package:flutter/scheduler.dart';
import 'package:flutter_smart_dialog/flutter_smart_dialog.dart';
import 'package:flutter_screenutil/flutter_screenutil.dart';
import 'package:permission_handler/permission_handler.dart';
import 'package:screen_capture_event/screen_capture_event.dart';
import 'package:sample_flutter/utils/AppUtil.dart';
import 'package:sample_flutter/utils/util.dart';

// 参考： https://stackoverflow.com/questions/65165453/how-to-implement-in-app-screenshot-in-flutter

class ScreenSample extends StatefulWidget {
  const ScreenSample({Key? key}) : super(key: key);

  @override
  _ScreenSampleState createState() => _ScreenSampleState();
}

class _ScreenSampleState extends State<ScreenSample> {
  GlobalKey rootWidgetKey = GlobalKey(); // 绘图key值
  final ScreenCaptureEvent screenListener = ScreenCaptureEvent();

  List<Uint8List> images = List.filled(0, Uint8List(0), growable: true);
  bool showModal = false;
  List<int> screenShot = [];
  String text = "inital screenShot listener";
  bool preventScreenshot = false;

  @override
  void initState() {
    screenListener.addScreenRecordListener((recorded) {
      ///Recorded was your record status (bool)
      setState(() {
        text = recorded ? "Start Recording" : "Stop Recording";
      });
    });

    screenListener.addScreenShotListener((filePath) {
      ///filePath only available for Android
      print('shot');
      setState(() {
        text = "Screenshot stored on : $filePath";
      });
    });

    ///You can add multiple listener ^-^
    screenListener.addScreenRecordListener((recorded) {
      print("Hi i'm 2nd Screen Record listener");
    });
    screenListener.addScreenShotListener((filePath) {
      print("Wohooo i'm 2nd Screenshot listener");
    });

    ///Start watch
    screenListener.watch();
    _requestPermission();
    super.initState();
  }

  @override
  void dispose() {
    ///Don't forget to dispose it to detach all the observer :)
    screenListener.dispose();
    super.dispose();
  }

  _requestPermission() async {
    Map<Permission, PermissionStatus> statuses = await [
      Permission.storage,
    ].request();

    final info = statuses[Permission.storage].toString();
    print(info);
  }

  // 截图
  _capturePng() async {
    try {
      RenderRepaintBoundary boundary = rootWidgetKey.currentContext
          ?.findRenderObject() as RenderRepaintBoundary;
      var image = await boundary.toImage(pixelRatio: 3.0);
      ByteData? byteData = await image.toByteData(format: ImageByteFormat.png);
      Uint8List? pngBytes = byteData?.buffer.asUint8List();
      images.add(pngBytes!);
      setState(() {});
      return pngBytes;
    } catch (e) {
      print(e);
    }
    return null;
  }

  void _show() {
    SmartDialog.show(
        isLoadingTemp: false,
        widget: Column(
          mainAxisAlignment: MainAxisAlignment.spaceBetween,
          crossAxisAlignment: CrossAxisAlignment.center,
          children: [
            Center(
              child: ClipRect(
                child: BackdropFilter(
                  filter: ImageFilter.blur(sigmaX: 5.0, sigmaY: 5.0),
                  child: Container(
                    height: 500.h,
                    width: 360.w,
                    padding: EdgeInsets.only(
                        left: 80.w, right: 80.w, top: 50.h, bottom: 20.h),
                    decoration: BoxDecoration(
                      // color: Colors.pink[100],
                      borderRadius: BorderRadius.circular(10),
                    ),
                    alignment: Alignment.center,
                    child: images.length > 0
                        ? Expanded(
                            child: FutureBuilder(
                                future: Utils.mergeImage(
                                    images[images.length - 1], context),
                                builder: (BuildContext context,
                                    AsyncSnapshot<dynamic> snapshot) {
                                  if (snapshot.hasData) {
                                    SchedulerBinding.instance
                                        ?.addPostFrameCallback((_) {
                                      screenShot = snapshot.data;
                                    });
                                    return Image.memory(snapshot.data,
                                        fit: BoxFit.fitWidth);
                                  }
                                  return Text('snapshot no data');
                                }),
                          )
                        : Text('no data'),
                  ),
                ),
              ),
            ),
            Container(
              height: 190.h,
              width: 360.w,
              padding: EdgeInsets.only(
                bottom: 30.0.h,
                top: 20.h,
              ),
              decoration: BoxDecoration(
                color: Colors.white,
                border: Border.all(
                  color: Colors.black,
                  width: 1,
                ),
                borderRadius: BorderRadius.only(
                  topLeft: Radius.circular(10.r),
                  topRight: Radius.circular(10.r),
                ),
              ),
              child: Column(children: [
                Text(
                  '分享',
                  style: TextStyle(fontSize: 16.sp),
                  textAlign: TextAlign.center,
                ),
                Container(
                  margin: EdgeInsets.symmetric(vertical: 10.0.r),
                  height: 30.0.h,
                  child: ListView(
                    // This next line does the trick.
                    scrollDirection: Axis.horizontal,
                    children: <Widget>[
                      Container(
                        width: 80.0.w,
                        color: Colors.red,
                      ),
                      Container(
                        width: 80.0.w,
                        color: Colors.blue,
                      ),
                      Container(
                        width: 80.0.w,
                        color: Colors.green,
                      ),
                      Container(
                        width: 80.0.w,
                        color: Colors.yellow,
                      ),
                      Container(
                        width: 80.0.w,
                        color: Colors.orange,
                      ),
                    ],
                  ),
                ),
                Expanded(
                  child: TextButton(
                    style: ButtonStyle(
                      foregroundColor:
                          MaterialStateProperty.all<Color>(Colors.blue),
                      overlayColor: MaterialStateProperty.resolveWith<Color?>(
                        (Set<MaterialState> states) {
                          if (states.contains(MaterialState.hovered))
                            return Colors.blue.withOpacity(0.04);
                          if (states.contains(MaterialState.focused) ||
                              states.contains(MaterialState.pressed))
                            return Colors.blue.withOpacity(0.12);
                          return null; // Defer to the widget's default.
                        },
                      ),
                    ),
                    onPressed: () {
                      // go back
                      SmartDialog.dismiss();
                    },
                    child: Text('取消'),
                  ),
                )
              ]),
            )
          ],
        ));
  }

  @override
  Widget build(BuildContext context) {
    return RepaintBoundary(
      key: rootWidgetKey,
      child: Container(
        width: MediaQuery.of(context).size.width,
        height: MediaQuery.of(context).size.height,
        padding: EdgeInsets.only(top: 10, bottom: 20, left: 15, right: 15),
        color: Color(0xFFD3F4FD),
        child: Container(
            width: MediaQuery.of(context).size.width - 20,
            height: MediaQuery.of(context).size.height - 30,
            decoration: BoxDecoration(
              color: Colors.white,
              boxShadow: [
                BoxShadow(
                  offset: Offset(0, 2),
                  blurRadius: 14,
                  color: Color(0x29000000),
                  spreadRadius: 0,
                )
              ],
              borderRadius: BorderRadius.circular(2),
            ),
            child: Column(
              crossAxisAlignment: CrossAxisAlignment.center,
              children: <Widget>[
                Center(child: Text('SSSSSSSS')),
                TextButton(
                  onPressed: () => {
                    _capturePng(),
                  },
                  child: Text('click me'),
                ),
                TextButton(
                  onPressed: () => {
                    setState(() => {images = []})
                  },
                  child: Text('clean'),
                ),
                TextButton(
                  onPressed: () => {
                    AppUtil.saveImage('', screenShot, isAsset: true),
                  },
                  child: Text('save'),
                ),
                Text('change'),
                Text(text, textAlign: TextAlign.center),
                const SizedBox(height: 10),
                TextButton(
                  style: TextButton.styleFrom(
                      backgroundColor: Theme.of(context).primaryColor),
                  onPressed: () {
                    setState(() {
                      preventScreenshot = !preventScreenshot;
                    });
                    screenListener.preventAndroidScreenShot(preventScreenshot);
                  },
                  child: Text(
                    preventScreenshot
                        ? "Allow Screenshot (ANDROID)"
                        : "Prevent Screenshot (ANDROID)",
                    style: const TextStyle(color: Colors.white),
                  ),
                ),
                TextButton(
                  child: Text('showDialog'),
                  onPressed: () => {_show()},
                ),
              ],
            )),
      ),
    );
  }
}
